package com.authine.cloudpivot.ext.controller.fileInfo.mainCom;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 **/

@RestController
@RequestMapping("/public/mainCompanyArchive")
@Slf4j
public class MainCompanyArchiveController extends BaseController {

    @Autowired
    CloudSqlService sqlService;


    @RequestMapping("/validSubmit")
    public ResponseResult validSubmit(@RequestBody Map<String, Object> map) {


        return getOkResponseResult("");
    }

    /**
     * 获取总公司档案列表数据
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("getFileInfoBaeList")
    public List getFileInfoBaeList(Integer page, Integer size) {

        String schemaCode = "fileInfoBase";

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        List<BizPropertyModel> list = getBizPropertyFacade().getListBySchemaCode(schemaCode, true);

        String codes = list.stream().filter(a -> !a.getDefaultProperty()).map(a -> a.getCode()).collect(Collectors.joining(","));

        StringBuilder sql = new StringBuilder("SELECT ").append(codes).append("  from ")
                .append(tableName);

        if (page != null && size != null) {
            if (page > 0) {
                page = (page - 1) * size;
            }
            String limit = String.format(" limit %d,%d", page, size);
            sql.append(limit);
        }
        List<Map<String, Object>> mapList = sqlService.getList(sql.toString());

        return mapList;
    }

    /**
     * 总公司级档案基础信息 新增 审批流完成后 数据写到基础表-总公司档案
     */
    @Async
    @RequestMapping("addFileInfoBase")
    public void addFileInfoBase(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.fileBaseAdd, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("Sheet1658798318323");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcess(map, approval);

            } catch (Exception e) {
                log.info("基础表-总公司档案  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    @Async
    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.VoidMainComArch, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("SheetVoidMainComArch");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcessToVoid(map, approval);

            } catch (Exception e) {
                log.info("基础表-总公司档案  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     * 调用存储过程
     ----总公司级档案基础信息同步存储过程       ----2023.03.22
     exec  SyncCorpFileInfo
     @TypeNumber     	nvarchar(50),       	----档案类型
     @ComNumber		nvarchar(20),		----主责公司
     @BaseFID		nvarchar(100),		----基础代码fid
     @BaseNumber		nvarchar(100),		----基础代码
     @FunNumber		nvarchar(50),		----职能
     @Serial			nvarchar(100),		----序号
     @Number			nvarchar(200),		----档案代码
     @Name			nvarchar(200),		----档案名称
     @Remark			nvarchar(200),		----备注
     @Desc			nvarchar(500),		----说明
     @Elec			nvarchar(10),		----电子版      1   √     0    x     2  /
     @DeptNumber		nvarchar(50),		----主责部门代码
     @PosNumber		nvarchar(50),		----主责岗代码
     @Auth			nvarchar(20),		----权限      1  五角    2  三角    3 √
     @Person			nvarchar(100),		----主责人
     @Auditor		nvarchar(100),		----审批人(与EAS登录账号保持一致   员工号+空格+姓名 例：02.0012 李四)
     @AuditDate		DATETIME		----审批时间
     *
     * @param map
     * @param approval
     */
    private void callProcess(Map<String, Object> map, String approval) {

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String TypeNumber  = MapUtils.getString(map, "archTypeNumber", "");//档案类型
        String ComNumber = MapUtils.getString(map, "mainComYingshe", "");//主责公司
        String BaseFID = MapUtils.getString(map, "relevBaseCode", "");//基础代码FID
        String BaseNumber = MapUtils.getString(map, "baseCode", "");//基础代码
        String FunNumber = MapUtils.getString(map, "znCode", "");//职能
        String Serial = MapUtils.getString(map, "xh", "");//序号
        String Number = MapUtils.getString(map, "fileCode", "");//档案代码
        String Name = MapUtils.getString(map, "fileName", "");//档案名称
        String Remark	 = MapUtils.getString(map, "remarks", "");//备注
        String Desc = MapUtils.getString(map, "des", "");//说明

        String elec = MapUtils.getString(map, "elec", "");//电子版      1   √     0    x     2  /
        String auth = "";
        if ("√".equals(elec)) {
            elec = "1";
            auth = "1";
        } else if ("×".equals(elec)) {//x
            elec = "0";
            auth = "3";
        } else {
            elec = "2";
            auth = "3";
        }

//        String elec = MapUtils.getString(map, "elec", "");//电子版      1   √     0    x     2  /
//        String Elec = "";
//        if ("√".equals(elec)) {
//            Elec = "1";
//        } else if ("x".equals(elec)) {
//            Elec = "0";
//        } else {
//            Elec = "2";
//        }

        String DeptNumber = MapUtils.getString(map, "defaultmainDeptId", "");//主责部门代码
        String PosNumber = MapUtils.getString(map, "mainPositionCode", "");//主责岗代码

        String purview = MapUtils.getString(map, "purview", "");//权限      1  五角    2  三角    3 √
        String Auth = "";
        purview = purview == null ? "" : purview;
        switch (purview) {
            case "★":
                Auth = "1";
                break;
            case "▲":
                Auth = "2";
                break;
            case "√":
                Auth = "3";
                break;
        }

        String Person = MapUtils.getString(map, "mainUser", "");//主责人
        String auditDate = MapUtils.getString(map, "auditDate", "");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCorpFileInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                TypeNumber, ComNumber, BaseFID, BaseNumber, FunNumber,
                Serial, Number, Name, Remark, Desc,
                elec,DeptNumber, PosNumber, auth, Person,
                auditDate,approval);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     * 调用作废存储过程
     ------总公司级档案作废 			----2023.03.22
     exec   CorpArchiveDisable
     @code     nvarchar(100)    ----档案代码
     */
    private void callProcessToVoid(Map<String, Object> map, String approval){

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String fileCode = MapUtils.getString(map, "fileCode", "");//档案代码



        String execSql = String.format("exec [HG_LINK].[hg].[dbo].CorpArchiveDisable '%s'",
                fileCode);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @param approvalType
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String approvalType) {
        String mainDeptCode = (String) bizObject.get("mainDeptCode");
        String activityCode = "";
        if ("01".equals(approvalType)) {
            String manageDeptCode = (String) bizObject.get("manageDeptCode");
            if (mainDeptCode.equals(manageDeptCode)) {
                activityCode = "Activity12";
            } else {
                activityCode = "Activity15";

            }
        } else if ("02".equals(approvalType)) {
            String funDepCode = (String) bizObject.get("funDepCode");
            if (mainDeptCode.equals(funDepCode)) {
                activityCode = "Activity17";
            } else {
                activityCode = "Activity21";
            }
        } else if ("03".equals(approvalType)) {
            String frameDeptCode = (String) bizObject.get("frameDeptCode");
            if (mainDeptCode.equals(frameDeptCode)) {
                activityCode = "Activity22";
            } else {
                activityCode = "Activity26";
            }
        }


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @param field
     * @param value
     * @param schemaCode
     * @return
     */
    private String existsBizObject(String field, String value, String schemaCode) {

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where ").append(field).append("='").append(value).append("'");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-总公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();
        //主责关联公司
        data.put("mainComGuanlian", map.get("maincom"));
        //主责公司代码
        data.put("mainCompanyCode", map.get("mainComYingshe"));
        //主责公司名称
        data.put("mainCompanyName", map.get("maincomName"));
        //档案代码
        data.put("fileCode", map.get("fileCode"));
        //档案名称
        data.put("fileName", map.get("fileName"));
        //备注
        data.put("remark", map.get("remarks"));
        //说明
        data.put("explains", map.get("des"));
        //职能关联
        data.put("fun", map.get("zn"));
        //职能代码
        data.put("funCode", map.get("znCode"));
        //职能
        data.put("funName", map.get("znName"));
        //电子版
        data.put("elec", map.get("elec"));
        //主责部门关联
        data.put("relevMainDept", map.get("MainDeptId"));
        //主责部门代码
        data.put("mainDeptCode", map.get("defaultmainDeptId"));
        //主责部门
        data.put("dept", map.get("MainDept"));
        //主责岗关联
        data.put("relevMainPosition", map.get("mainPositionId"));
        //主责岗代码
        data.put("mainPositionCode", map.get("mainPositionCode"));
        //主责岗
        data.put("mainPosition", map.get("mainPostionName"));
        //档案类型关联
        data.put("relevFileType", map.get("typeName"));
        //档案类型
        data.put("fileType", map.get("archTypeNumber"));
        //总公司授权信息
        data.put("mainCompanyAuthInfo", map.get("purview"));
        //纸质数量
//        data.put("paperNum",map.get(""));
        //01授权
//        data.put("one",map.get("1"));
        //02授权
//        data.put("two",map.get("1"));
        //03授权
//        data.put("three",map.get("1"));
        //04授权
//        data.put("four",map.get("1"));
        //05授权
//        data.put("five",map.get("1"));
        //06授权
//        data.put("six",map.get("1"));
        //07授权
//        data.put("seven",map.get("1"));
        //08授权
//        data.put("eight",map.get("1"));
        //09授权
//        data.put("nine",map.get("1"));
        //10授权
//        data.put("ten",map.get("1"));
        //工作说明
        data.put("jobDesc", map.get("refDes"));
        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);
        //关联基础代码
        data.put("relevBaseCode", map.get("basicCode"));
        //基础代码
        data.put("baseCode", map.get("baseCode"));
        //序号
        data.put("serialNo", map.get("xh"));

        //主责人
        data.put("mainUser", map.get("mainUser"));

        return data;
    }


}
